package com.imooc.miaosha.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.imooc.miaosha.vo.JedisResp;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class RedisCheck {
    static final Map<String, Jedis> jedisMap = Maps.newHashMap();
    public static final int NORMAL = 1;
    public static final int AB_NORMAL = 0;

    public Jedis createJedis(String host, Integer port) {
        return new Jedis(host, port);
    }

    public Jedis createJedis(String host, Integer port, String auth) {
        Jedis jedis = new Jedis(host, port);
        jedis.auth(auth);
        return jedis;
    }

    public Map<String, Object> addJedis(String jedisNickName, Jedis jedis, String pass) {
        Map<String, Object> respMap = Maps.newHashMap();
        if (StringUtils.isNotEmpty(pass)) {
            jedis.auth(pass);
        }
        try {
            if (!jedis.ping().equals("PONG")) {
                respMap.put("code", 0);
                respMap.put("msg", "连接不上,监听失败");
                return respMap;
            }
            RedisCheck.jedisMap.put(jedisNickName, jedis);
            respMap.put("code", 1);
            respMap.put("msg", "连接上了,监听成功");
        } catch (Exception e) {
            respMap.put("code", 0);
            respMap.put("msg", "连接不上,连接发生异常,监听失败");
            return respMap;
        }
        return respMap;
    }

    public Map<String, Jedis> foeachAllJedis() {
        return jedisMap;
    }

    public List<JedisResp> pingAllJedisInMap() {
        List<JedisResp> respList = Lists.newArrayList();
        Set<String> keySet = jedisMap.keySet();
        for (String key : keySet) {
            System.out.println(key);
            JedisResp jedisResp = new JedisResp();
            Jedis jedis = jedisMap.get(key);
            jedisResp.setNickName(key);
            if (jedis.ping().equals("PONG")) {
                jedisResp.setStatus(RedisCheck.NORMAL);
            } else {
                jedisResp.setStatus(RedisCheck.AB_NORMAL);
            }
            respList.add(jedisResp);
        }
        return respList;
    }
}
